package com.b2c.erp.controller.funds;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.b2c.entity.api.ApiResult;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.funds.OrderSettlementPddEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.funds.OrderSettlementPddService;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

@RequestMapping("/funds")
@Controller
public class OrderSettlementPddController {
    @Autowired
    private ShopService shopService;
    private static Logger log = LoggerFactory.getLogger(OrderSettlementPddController.class);
    @Resource
    private OrderSettlementPddService orderSettlementPddService;

    @RequestMapping("/order_settlement_detail_pdd")
    public String orderSettlementDetail(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = 100;//DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }

        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        // 有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId, 5);// type=5是拼多多
        model.addAttribute("shops", shops);
        model.addAttribute("shopId", 5);

        String startTime = "";
        if (StringUtils.hasText(request.getParameter("startTime")))
        startTime = request.getParameter("startTime");
        model.addAttribute("startTime", startTime);

        String endTime = "";
        if (StringUtils.hasText(request.getParameter("endTime")))
            endTime = request.getParameter("endTime");
        model.addAttribute("endTime", endTime);

        String orderSn = null;
        if (StringUtils.hasText(request.getParameter("orderSn")))
            orderSn = request.getParameter("orderSn");
        model.addAttribute("orderSn", orderSn);


        var result = orderSettlementPddService.getOrderSettlementList(pageIndex,pageSize,  orderSn, startTime, endTime);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        model.addAttribute("pageTitle", "订单结算 - 拼多多");
        model.addAttribute("view", "order_settle_pdd");
        model.addAttribute("pView", "pd");
        return "funds/order_settlement_detail_pdd";
    }

    @RequestMapping("/order_settlement_pdd_list")
    public String orderSettlementList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = 100;//DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }

        String startDate = "";
        if (StringUtils.hasText(request.getParameter("startDate")))
            startDate = request.getParameter("startDate");
        // else
        //     startDate = DateUtil.dateToString(DateUtil.beforeDayDate(30), "yyyy-MM-dd");
        model.addAttribute("startDate", startDate);
        String endDate = "";
        if (StringUtils.hasText(request.getParameter("endDate")))
            endDate = request.getParameter("endDate");
        // else
        //     endDate = DateUtil.getCurrentDate();
        model.addAttribute("endDate", endDate);
        String orderSn = null;
        if (StringUtils.hasText(request.getParameter("orderSn")))
            orderSn = request.getParameter("orderSn");
        model.addAttribute("orderSn", orderSn);

        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        // 有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId, 5);// type=5是拼多多
        model.addAttribute("shops", shops);
        model.addAttribute("shopId", 5);
        var result = orderSettlementPddService.getList(pageIndex,pageSize,orderSn,startDate,endDate);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        model.addAttribute("pageTitle", "订单结算 - 拼多多");
        model.addAttribute("view", "order_settlement_pdd");
        model.addAttribute("pView", "pd");
        return "funds/order_settlement_pdd_list";
    }

    @RequestMapping("/order_settlement_pdd_import")
    public String orderSettlementImport(Model model, HttpServletRequest request) {
        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        // 有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId, 5);// type=5是拼多多
        model.addAttribute("shops", shops);
        model.addAttribute("shopId", 5);
        model.addAttribute("view", "order_settlement_pdd");
        model.addAttribute("pView", "pd");
        return "funds/order_settlement_pdd_import";
    }

    @ResponseBody
    @RequestMapping(value = "/order_settlement_pdd_import_ajax", method = RequestMethod.POST)
    public ApiResult<List<OrderSettlementPddEntity>> orderSendExcel(@RequestParam("excel") MultipartFile file,
            HttpServletRequest req) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********导入pdd结算数据，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");
        InputStream fis = null;
        fis = new FileInputStream(destFileName);
        if (fis == null)
            return new ApiResult<>(502, "没有文件");

        Workbook workbook = null;

        try {
            if (fileName.toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (fileName.toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(fis);
            }
            // workbook = new HSSFWorkbook(fis);
        } catch (Exception ex) {
            log.info("/***********导入pdd结算数据***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        if (workbook == null)
            return new ApiResult<>(502, "未读取到Excel文件");

        /**************** 开始处理批批网csv订单 ****************/
        // 订单list
        List<OrderSettlementPddEntity> list = new ArrayList<>();
        Sheet sheet = null;

        try {
            sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();// 最后一行索引
            Row row = null;

            for (int i = 5; i <= lastRowNum; i++) {
                try {
                    if(i ==1404){
                        String s="";
                    }
                    row = sheet.getRow(i);
                    if(row == null) continue;
                    String orderSn = "";
                    Cell cell0 = row.getCell(0);
                    if (cell0 != null)
                        orderSn = cell0.getStringCellValue();

                    log.info("/***********导入pdd订单结算数据**[" + i + "]**读取到订单编号:" + orderSn + "***********/");

                    orderSn = orderSn.replace("\t", "").trim();
                    OrderSettlementPddEntity r = new OrderSettlementPddEntity();
                    r.setId(Long.parseLong(i+""));
                    r.setOrderSn(orderSn);
                    String settlementTime = "";
                    Cell cell1 = row.getCell(1);
                    if (cell1 == null)
                        continue;
                    if (HSSFDateUtil.isCellDateFormatted(cell1)) {// 日期类型
                        // 短日期转化为字符串
                        Date date = cell1.getDateCellValue();
                        if (date != null) {
                            // 标准0点 1970/01/01 08:00:00
                            if (date.getTime() % 86400000 == 16 * 3600 * 1000
                                    && cell1.getCellStyle().getDataFormat() == 14) {
                                settlementTime = new SimpleDateFormat("yyyy-MM-dd").format(date);
                            } else {
                                settlementTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                            }
                        }
                    }

                    r.setSettlementTime(settlementTime);
                    Double income = row.getCell(2).getNumericCellValue();
                    r.setIncome(income);
                    Double expend = row.getCell(3).getNumericCellValue();
                    r.setExpend(expend);
                    String type = row.getCell(4).getStringCellValue();
                    r.setType(type);
                    String remark = row.getCell(5).getStringCellValue();
                    r.setRemark(remark);
                    String description = row.getCell(6).getStringCellValue();
                    r.setDescription(description);

                    list.add(r);
                } catch (Exception e) {
                    log.info("/***********读取pdd订单结算数据**读取数据异常[" + i + "]**" + e.getMessage() + "***********/");
                }
            }

        } catch (Exception ex) {
            log.info("/***********导入pdd订单结算数据****出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        return new ApiResult<>(0, "SUCCESS", list);
    }

    @ResponseBody
    @RequestMapping(value = "/order_settlement_pdd_import_submit", method = RequestMethod.POST)
    public ApiResult<String> orderExcelImportSubmit(@RequestBody OrderSettlementPddImportSubmitReq req) {
       if (req.getShopId() == null || req.getShopId() == 0)
           return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有shopId");

        List<OrderSettlementPddEntity> orderList = req.getOrderList();
        if (orderList == null || orderList.size() == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有orderList");
            
        Integer shopId = req.getShopId();
       

        ResultVo<String> resultVo = orderSettlementPddService.importExcelSettlementList(orderList,shopId);

        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS", resultVo.getData());
        } else return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
    }


    @RequestMapping(value = "/order_settlement_detail_pdd_export", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public void outExport(HttpServletRequest request, HttpServletResponse response) {
        String startTime = null;
        String endTime = null;
        if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
            startTime = request.getParameter("startTime");
        }
        if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
            endTime = request.getParameter("endTime");

        }
        // 按条件搜索
        var list = orderSettlementPddService.getOrderSettlementList(null,startTime, endTime);
        

        /*************** 根据店铺查询订单导出的信息 *****************/
        String excelFileName = "";// excel文件名前缀

        // 创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        // 第一行为空
        row = sheet.createRow(0);

        cell = row.createCell(0);
        cell.setCellValue("订单号");

        cell = row.createCell(1);
        cell.setCellValue("下单时间");

        cell = row.createCell(2);
        cell.setCellValue("发货时间");

        cell = row.createCell(3);
        cell.setCellValue("订单金额");

        cell = row.createCell(4);
        cell.setCellValue("订单收入");

        cell = row.createCell(5);
        cell.setCellValue("订单支出");
        cell = row.createCell(6);
        cell.setCellValue("结余");
        cell = row.createCell(7);
        cell.setCellValue("订单状态");

        

        int currRowNum = 0;
        // 循环写入数据
        for (int i = 0; i < list.size(); i++) {
            currRowNum++;
            // 写入订单
            var orderVo = list.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            //订单编号
            cell = row.createCell(0);
            cell.setCellValue(orderVo.getOrderSn());
            //订单编号
            cell = row.createCell(1);
            cell.setCellValue(orderVo.getOrderTime());
            //发货时间
            cell = row.createCell(2);
            cell.setCellValue(orderVo.getShippingTime());
            cell = row.createCell(3);
            cell.setCellValue(orderVo.getPayAmount());
            cell = row.createCell(4);
            cell.setCellValue(orderVo.getIncome());
            cell = row.createCell(5);
            cell.setCellValue(orderVo.getExpend());
            BigDecimal income = new BigDecimal(orderVo.getIncome());
            BigDecimal expend = new BigDecimal(orderVo.getExpend());
            BigDecimal jieyu = income.add(expend);
            cell = row.createCell(6);
            Double jieyud = jieyu.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            
            cell.setCellValue(jieyud);
            cell = row.createCell(7);
            cell.setCellValue(orderVo.getOrderStatus() + "-"+orderVo.getRefundStatus()+"-"+orderVo.getAuditStatus()+"-"+orderVo.getSendStatus());

        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((excelFileName + date + ".xls").getBytes("GBK"),
                            "ISO8859_1")
                    + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }

        return;
    }

}
